const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
  throwOnNotFound: true
})
const _ = db.command;
const $ = db.command.aggregate
const globalConfig = require('../../config/index')

module.exports = async (event, context, root) => {
  const {
    OPENID
  } = cloud.getWXContext();
  // 验证该接口是否需要验证注册
  let parame = event.data;
//   try {
    let where = {
      openId: OPENID
    }

	var result = await Promise.all([  
		// 查询总记录数  
		db.collection('caipiao_log').count(),  
		// 查询 winnings 大于 0 的记录数  
		db.collection('caipiao_log').where({  
		  openId: OPENID,  
		  winnings: _.gt(0) // 注意使用 gt 而不是 gte  
		}).count(),  
		// 聚合查询 winnings 的总和（不考虑 openId）  
		db.collection('caipiao_log').aggregate()
		.group({
			_id: null,
			winning_records: $.sum('$winnings')
		})
		.end()
	])

    var res = {
      errcode: 200,
      msg: '操作成功！',
      result: {
		total_records:result[0].total,
		total_winnings:result[1].total,
		winning_records:result[2].list[0]&&result[2].list[0].winning_records
	  },
	  where:where,
      success: true,
      timestamp: new Date().getTime()
    }
//   } catch (error) {
//     var error_type = globalConfig.common.error_type(error.errCode);
//     var res = {
//       errcode: 404,
//       error: error,
//       msg: error_type.type,
//       result: error,
//       success: false,
//       timestamp: new Date().getTime()
//     }
//   }
  return res;
}
